# --------------------------------------------------------
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Modified by Wang Youjie
# Date: 2021/10/31
# Detail: this is a Window-based Transformer, but we use 8*6 non-overlap window to fit the input
# image resolution(384, 288) which the height is not equal to width, and the 8*6 is the ratio of the origin image size,
# also yo can use the size of 12*9, 16*12 and so on
# --------------------------------------------------------
import torch
import torch.nn as nn
import numpy as np
from einops import rearrange
from torch import einsum
from timm.models.layers import DropPath


def get_relative_distances(window_size: tuple):
    indices = torch.tensor(np.array([[x, y] for x in range(window_size[0]) for y in range(window_size[1])]))
    distances = indices[None, :, :] - indices[:, None, :]
    return distances


class WindowAttention(nn.Module):
    def __init__(self, dim, heads, head_dim, window_size, relative_pos_embedding, attn_drop=0.):
        super().__init__()
        inner_dim = head_dim * heads
        self.heads = heads
        self.scale = head_dim ** -0.5
        self.window_size = window_size
        self.relative_pos_embedding = relative_pos_embedding # (13, 13)

        self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
        if self.relative_pos_embedding:
            self.relative_indices = get_relative_distances(window_size) + torch.tensor(window_size) - 1
            self.pos_embedding = nn.Parameter(torch.randn(2 * window_size[0] - 1, 2 * window_size[1] - 1))
        else:
            self.pos_embedding = nn.Parameter(torch.randn(window_size[0] ** 2, window_size[1] ** 2))
        self.attn_drop = nn.Dropout(attn_drop)
        self.to_out = nn.Linear(inner_dim, dim)

    def forward(self, x):
        b, n_h, n_w, _, h = *x.shape, self.heads  # [1, 96, 72, _, 3]
        qkv = self.to_qkv(x).chunk(3, dim=-1)  # [(1,96,72,96), (1,96,72,96), (1,96,72,96)]
        nw_h = n_h // self.window_size[0]  # 12
        nw_w = n_w // self.window_size[1]  # 12
        # 分成 h/M * w/M 个窗口
        q, k, v = map( lambda t: rearrange(t, 'b (nw_h w_h) (nw_w w_w) (h d) -> b h (nw_h nw_w) (w_h w_w) d', h=h, w_h=self.window_size[0], w_w=self.window_size[1]), qkv)
        # q, k, v : (1, 3, 144=12*12, 48=6*8, 32)
        # 按窗口个数的self-attention
        dots = einsum('b h w i d, b h w j d -> b h w i j', q, k) * self.scale  # (1,3,144,48,48)

        if self.relative_pos_embedding:
            dots += self.pos_embedding[self.relative_indices[:, :, 0], self.relative_indices[:, :, 1]]
        else:
            dots += self.pos_embedding

        attn = dots.softmax(dim=-1)  # (1,3,144,48,48)
        attn = self.attn_drop(attn)
        out = einsum('b h w i j, b h w j d -> b h w i d', attn, v)
        out = rearrange(out, 'b h (nw_h nw_w) (w_h w_w) d -> b (nw_h w_h) (nw_w w_w) (h d)', h=h, w_h=self.window_size[0], w_w=self.window_size[1], nw_h=nw_h, nw_w=nw_w) # (1, 96, 72, 96) # 窗口合并
        out = self.to_out(out)
        return out


class FeedForward(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x


class Residual(nn.Module):
    def __init__(self, fn):
        super().__init__()
        self.fn = fn

    def forward(self, x, **kwargs):
        return self.fn(x, **kwargs) + x


class PreNorm(nn.Module):
    def __init__(self, dim, fn):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.fn = fn

    def forward(self, x, **kwargs):
        return self.fn(self.norm(x), **kwargs)


class SwinBlock(nn.Module):
    def __init__(self, dim, heads, head_dim, mlp_dim, window_size=(8, 6), relative_pos_embedding=True, attn_drop=0, drop_path=0.,
                 drop=0., act_layer=nn.GELU):
        super().__init__()
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.attention_block = PreNorm(dim, WindowAttention(dim=dim, heads=heads,
                                                            head_dim=head_dim, window_size=window_size,
                                                            relative_pos_embedding=relative_pos_embedding,
                                                            attn_drop=attn_drop))
        self.mlp_block = PreNorm(dim, FeedForward(dim, hidden_features=mlp_dim, act_layer=act_layer, drop=drop))

    def forward(self, x):
        x = self.attention_block(x)
        x = x + self.drop_path(x)

        x = self.mlp_block(x)
        x = x + self.drop_path(x)
        return x


class PatchMerging(nn.Module):
    def __init__(self, in_channels, out_channels, downscaling_factor):
        super().__init__()
        self.downscaling_factor = downscaling_factor
        self.patch_merge = nn.Unfold(kernel_size=downscaling_factor, stride=downscaling_factor, padding=0)
        self.linear = nn.Linear(in_channels * downscaling_factor ** 2, out_channels)

    def forward(self, x):
        b, c, h, w = x.shape  # 1, 3, 384, 288
        new_h, new_w = h // self.downscaling_factor, w // self.downscaling_factor  # 96, 72
        x = self.patch_merge(x) # (1, 48=4*4*3, 6912=96*72)
        x = x.view(b, -1, new_h, new_w).permute(0, 2, 3, 1)  # (1, h, w, 4c): (1, 96, 72, 48)
        x = self.linear(x)  # (1, 96, 72, 96)
        return x


if __name__ == '__main__':
    img = torch.rand((1, 3, 384, 288))
    patch_partition = PatchMerging(in_channels=3, out_channels=96, downscaling_factor=4)
    pp = patch_partition(img)  # (b, h, w, c):[1, 96, 72, 96]
    sb = SwinBlock(dim=96, heads=3, head_dim=32, mlp_dim=96*4, window_size=(8, 6), relative_pos_embedding=True)
    x = sb(pp)  # B H W C
    x = x.permute(0, 3, 1, 2)
    print(x.shape)
